package com.jwater.core.common.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import jwater.org.dom4j.Document;
import jwater.org.dom4j.DocumentHelper;
import jwater.org.dom4j.Element;
import jwater.org.dom4j.io.SAXReader;
import jwater.org.springframework.core.io.Resource;
import jwater.org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import jwater.org.springframework.core.io.support.ResourcePatternResolver;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class XmlConfig extends XmlData {
    private static final long serialVersionUID = -2523473621360022128L;

    /**
     * 加载配置
     *
     * @param is
     * @throws Exception
     */
    public void loadConfig(InputStream is) throws Exception {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);
        this.setDoc(doc);
        is.close();
    }

    /**
     * 加载配置
     *
     * @param file
     * @throws Exception
     */
    public void loadConfig(File file) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        loadConfig(fis);
    }

    /**
     * @param locationPattern classpath*:/conf/jwater.job.xml file:/conf/jwater.job.xml
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public void loadConfig(String locationPattern) throws Exception {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resources[] = resolver.getResources(locationPattern);
        if (resources == null || resources.length == 0) {
            return;
        }
        SAXReader reader = new SAXReader();
        Document baseDoc = reader.read(resources[0].getInputStream());
        for (int i = 1; i < resources.length; i++) {
            Document doc = reader.read(resources[i].getInputStream());
            List<Element> elements = doc.getRootElement().elements();
            for (Element element : elements) {
                baseDoc.getRootElement().add(element.detach());
            }
        }
        this.setDoc(baseDoc);
    }

    /**
     * 从文本解析xml
     *
     * @param text
     * @throws Exception
     */
    public void loadConfigFromText(String text) throws Exception {
        Document doc = DocumentHelper.parseText(text);
        this.setDoc(doc);
    }
}
